from approval_service.approval.mappers.advance_approval_mapper import AdvanceApprovalMapper
from approval_service.approval.mappers.approval_mapper import ApprovalMapper
from approval_service.approval.service.client.travel_client import TravelClient
from approval_service.approval.service.client.user_client import UserClient
from commons.entity.enum.advance_approval_enum import AdvanceApprovalEnum
from commons.entity.enum.travel_approval_enum import TravelApprovalEnum
from commons.entity.po.advance_approval import AdvanceApproval
from commons.entity.po.approval import Approval
from commons.entity.query.advance_approval_query import AdvanceApprovalQuery
from commons.entity.query.approval_query import ApprovalQuery
from commons.entity.vo.pagination_result_vo import PaginationResultVO
from commons.entity.vo.travel_vo import TravelVO
from commons.utils.copy_tools import CopyTools


class AdvanceApprovalService:
    def __init__(self):
        self.advance_approval_mapper = AdvanceApprovalMapper()
        self.travel_client = TravelClient()
        self.user_client = UserClient()
        self.approval_mapper = ApprovalMapper()

    def find_list_by_param(self, advance_approval_query=None):
        """
        业务逻辑：根据多个参数查询审批预支款申请记录列表。
        :param advance_approval_query: AdvanceApprovalQuery 实例，包含查询过滤条件。
        :return: 包含审批预支款对象。
        """
        print("AdvanceApprovalService find_list_by_param")
        print(advance_approval_query)

        return self.advance_approval_mapper.select_list(AdvanceApproval, advance_approval_query)

    def find_count_by_param(self, advance_approval_query=None):
        """
        业务逻辑：根据多个参数统计审批预支款申请记录数量。
        :param advance_approval_query: AdvanceApprovalQuery 实例，包含查询过滤条件。
        :return: 符合条件的审批预支款申请记录数量。
        """
        print("AdvanceApprovalService find_count_by_param")
        print(advance_approval_query)

        return self.advance_approval_mapper.select_count(AdvanceApproval, advance_approval_query)

    def get_advance_approval_by_advance_approval_id(self, advance_approval_id):
        """
        业务逻辑：获取单条审批预支款申请记录
        :param advance_approval_id: str
        :return: Approval 预支款审批记录字典或 None
        """
        print("AdvanceApprovalService get_advance_approval_by_advance_approval_id ")
        print(advance_approval_id)

        return self.advance_approval_mapper.select_by_advance_approval_id(advance_approval_id)

    def add(self, advance_approval_bean):
        """
        业务逻辑：添加一个新的审批预支款申请记录。
        :param advance_approval_bean: AdvanceApproval 类实例，包含审批记录信息。
        :return: 插入操作是否成功（True/False）。
        """
        print("AdvanceApprovalService add advance_approval")
        print(advance_approval_bean)

        return self.advance_approval_mapper.insert(advance_approval_bean)

    def add_batch(self, advance_approval_list_bean):
        """
        业务逻辑：批量添加审批预支款申请记录。
        :param advance_approval_list_bean: 包含多个 AdvanceApproval 类实例的列表，包含需要插入的审批记录信息。
        :return: 插入操作成功的审批记录数量。
        """
        print("AdvanceApprovalService add_batch advance_approval")
        print(advance_approval_list_bean)

        if not advance_approval_list_bean:
            print("No advance approvals to add. The input list is either null or empty.")
            return 0

        return self.advance_approval_mapper.insert_batch(advance_approval_list_bean)

    def add_or_update_batch(self, advance_approval_list_bean):
        """
        业务逻辑：批量插入或更新审批预支款记录信息。
        :param advance_approval_list_bean: 包含多个 AdvanceApproval 类实例的列表，包含需要插入或更新的审批记录信息。
        :return: 插入或更新成功的审批记录数量。
        """
        print("AdvanceApprovalService add_or_update_batch advance_approval")
        print(advance_approval_list_bean)

        if not advance_approval_list_bean:
            print(
                "No advance approvals to add or update. The input list is either null or empty.")
            return 0

        return self.advance_approval_mapper.insert_or_update_batch(AdvanceApproval, advance_approval_list_bean)

    def update_by_param(self, advance_approval_bean, advance_approval_query):
        """
        业务逻辑：根据多个条件更新审批预支款记录信息。
        :param advance_approval_bean: AdvanceApproval 类实例或字典，包含需要更新的字段及其新值。
        :param advance_approval_query: AdvanceApprovalQuery 类实例或字典，包含用于定位记录的过滤条件。
        :return: 更新成功的数量。
        """
        print("AdvanceApprovalService update_by_param")
        print(advance_approval_bean)
        print(advance_approval_query)

        return self.advance_approval_mapper.update_by_params(AdvanceApproval, advance_approval_bean,
                                                             advance_approval_query)

    def delete_by_param(self, advance_approval_query):
        """
        业务逻辑：根据多个条件删除审批预支款记录信息。
        :param advance_approval_query: AdvanceApprovalQuery 类实例或字典，包含用于定位记录的过滤条件。
        :return: 删除成功的数量。
        """
        print("AdvanceApprovalService delete_by_param")
        print(advance_approval_query)

        return self.advance_approval_mapper.delete_by_param(AdvanceApproval, advance_approval_query)

    def update_advance_approval_by_advance_approval_id(self, advance_approval_bean, advance_approval_id):
        """
        业务逻辑：根据 advance_approval_id 更新审批预支款记录信息。
        :param advance_approval_id: str
        :param advance_approval_bean: AdvanceApproval 类实例，包含需要更新的审批预支款记录属性。
        :return: 更新成功信息或错误信息。
        """
        print("AdvanceApprovalService update_advance_approval_by_advance_approval_id ")
        print(
            f"advance_approval_id: {advance_approval_id}, advance_approval_bean: {advance_approval_bean}")

        return self.advance_approval_mapper.update_by_advance_approval_id(advance_approval_bean, advance_approval_id)

    def delete_advance_approval_by_advance_approval_id(self, advance_approval_id):
        """
        业务逻辑：根据 advance_approval_id 删除审批预支款记录。
        :param advance_approval_id: str
        :return: 删除成功或错误。
        """
        print("AdvanceApprovalService delete_advance_approval_by_advance_approval_id ")
        print(advance_approval_id)

        return self.advance_approval_mapper.delete_by_advance_approval_id(advance_approval_id)

    def get_approve_advance_record(self, user_id, page_no, page_size):
        """
        获取审批预支款记录并返回分页数据。
        :param user_id: 财务人员ID
        :param page_no: 当前页码
        :param page_size: 每页显示数量
        :return: PaginationResultVO 对象，包含分页结果和审批记录
        """
        print("AdvanceApprovalService get_approve_advance_record")
        print(
            f"user_id: {user_id}, page_no: {page_no}, page_size: {page_size}")

        advance_approval_query = AdvanceApprovalQuery()
        advance_approval_query.finance_id = user_id

        # 获取审批预支款记录列表
        advance_approval_list = self.find_list_by_param(advance_approval_query)
        if not advance_approval_list:
            return None

        advance_approval_map = {
            approval.advance_id: approval for approval in advance_approval_list
        }

        # 获取所有出差申请ID
        travel_id_list = list(
            set([approval.advance_id for approval in advance_approval_list]))
        travel_list = self.travel_client.get_all_travels_by_id_list(
            travel_id_list)

        # 获取所有出差申请人信息
        user_id_list = list(set([travel.user_id for travel in travel_list]))
        user_list = self.user_client.get_all_users_by_id_list(user_id_list)
        user_map = {user.user_id: user for user in user_list}

        travel_vo_list = []

        for travel in travel_list:
            # 复制 Travel 对象到 TravelVO
            travel_vo = CopyTools.copy(travel, TravelVO)

            # 获取对应的审批预支款记录
            advance_approval = advance_approval_map.get(travel.travel_id)
            travel_vo.payment = advance_approval.payment

            # 获取审批记录
            approval_query = ApprovalQuery()
            approval_query.travel_id = travel.travel_id
            approval_list = self.approval_mapper.select_list(
                Approval, approval_query)

            approval = approval_list[0]
            travel_vo.advance_rejection = approval.advance_rejection
            travel_vo.approval_id = approval.approval_id
            travel_vo.advance_status = approval.advance_approval
            travel_vo.advance_status_name = AdvanceApprovalEnum.get_by_type(
                approval.advance_approval).msg

            # 获取出差申请人信息
            user = user_map.get(travel.user_id)
            travel_vo.user_name = user.name
            travel_vo.user_phone = user.phone
            travel_vo.user_email = user.email
            travel_vo.position = user.position

            # 计算预算
            travel_vo.budget = (travel_vo.food_cost +
                                travel_vo.hotel_cost + travel_vo.transport_cost)

            travel_vo_list.append(travel_vo)

        # 分页逻辑
        count = len(travel_vo_list)

        # start = (page_no - 1) * page_size
        # end = min(start + page_size, count)

        # total_page = count // page_size if count % page_size == 0 else (
        #     count // page_size) + 1

        return PaginationResultVO(
            count, page_size, page_no, 0, travel_vo_list)

        return result

    def get_advance_approval_by_travel_id(self, travel_id):
        """
        业务逻辑：获取单条审批预支款申请记录
        :param travel_id: str
        :return: Approval 预支款审批记录字典或 None
        """
        print("AdvanceApprovalService get_advance_approval_by_travel_id ")
        print(travel_id)

        return self.advance_approval_mapper.select_by_advance_travel_id(travel_id)
